package com.reagent.handler;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureGenerationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.reagent.response.Result;
import com.reagent.response.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description: 全局异常处理
 * @ClassNmae: GlobalExceptionHandler
 * @Author: HeYue
 * @DateTime: 2020-11-14 17:39
 **/
@ControllerAdvice
@RestController
@Slf4j
public class GlobalExceptionHandler {

    //总异常处理
    @ExceptionHandler(Exception.class)
    public Result error(Exception e) {
        e.printStackTrace();
        log.error(ResultCode.COMMON_ERROR.getMessage());
        return Result.error().code(ResultCode.COMMON_ERROR.getStatus())
                .message(ResultCode.COMMON_ERROR.getMessage());
    }

    /*JWT-Token异常*/
    //令牌过期
    @ExceptionHandler(TokenExpiredException.class)
    public Result error(TokenExpiredException e) {
//        e.printStackTrace();
        log.error(ResultCode.TOKEN_EXPIRED.getMessage());
        return Result.error().code(ResultCode.TOKEN_EXPIRED.getStatus())
                .message(ResultCode.TOKEN_EXPIRED.getMessage());
    }

    //签名不一致
    @ExceptionHandler(SignatureGenerationException.class)
    public Result error(SignatureGenerationException e) {
//        e.printStackTrace();
        log.error(ResultCode.TOKEN_SIGNATUREGENERATION.getMessage());
        return Result.error().code(ResultCode.TOKEN_SIGNATUREGENERATION.getStatus())
                .message(ResultCode.TOKEN_SIGNATUREGENERATION.getMessage());
    }

    //算法异常
    @ExceptionHandler(AlgorithmMismatchException.class)
    public Result error(AlgorithmMismatchException e) {
//        e.printStackTrace();
        log.error(ResultCode.TOKEN_ALGORITHMMISMATCH.getMessage());
        return Result.error().code(ResultCode.TOKEN_ALGORITHMMISMATCH.getStatus())
                .message(ResultCode.TOKEN_ALGORITHMMISMATCH.getMessage());
    }

    //有载负荷失效
    @ExceptionHandler(InvalidClaimException.class)
    public Result error(InvalidClaimException e) {
//        e.printStackTrace();
        log.error(ResultCode.TOKEN_INVALIDCLAIM.getMessage());
        return Result.error().code(ResultCode.TOKEN_INVALIDCLAIM.getStatus())
                .message(ResultCode.TOKEN_INVALIDCLAIM.getMessage());
    }
}
